package programs;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 线程池,把线程创建好,放在池子里
 * 线程用完了,不是还给系统,而是放回池子里,以备下一次用
 */
public class TestThreadPool {

    public static void main(String[] args) throws InterruptedException {
        MyThreadPool pool = new MyThreadPool(10);
        for (int i = 0; i < 50; i++) {
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello thread");
                }
            });
        }
        for (int i = 0; i < 50; i++) {
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("新的任务");
                }
            });
        }
    }


    public static void main1(String[] args) throws InterruptedException {
        // 创建一个固定线程的线程池
        ExecutorService pool = Executors.newFixedThreadPool(10);
        // 创建一个自动扩容的线程池
        // Executors.newCachedThreadPool();
        // 创建一个只有一个线程的线程池
        // Executors.newSingleThreadExecutor();
        // 创建一个带有定时器功能的线程池
        // Executors.newScheduledThreadPool();
        for (int i = 0; i < 100; i++) {
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello threadPoll");
                }
            });
        }
    }

}

class MyThreadPool {
    // 描述一个任务 Runnable
    // 使用一个数据结构组织任务  -- 阻塞队列
    private static BlockingDeque<Runnable> queue = new LinkedBlockingDeque<>();

    // 描述一个工作线程,工作线程的功能就是从队列中取任务来执行
    static class Worker extends Thread{
        @Override
        public void run() {
            while (true){
                try {
                    Runnable runnable = queue.take();
                    runnable.run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 创建一个数据结构来组织线程
    private List<Thread> workers = new ArrayList<>();
    public MyThreadPool(int n) {
        // 创建若干个线程,放到上述数组
        for (int i = 0; i < n; i++) {
            Worker worker = new Worker();
            worker.start();
            workers.add(worker);
        }
    }

    // 创建一个方法,允许程序员放任务到线程池
    public void submit(Runnable runnable){
        try {
            queue.put(runnable);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}